<?php

declare(strict_types=1);

namespace app\wechat\controller\admin;

use think\Request;
use think\Response;
use think\facade\Db;
use sheep\controller\Backend;
use app\wechat\facade\Wechat;
use app\wechat\model\Menu as MenuModel;
use sheep\exception\SheepException;

class Menu extends Backend
{

    protected $wechat = null;
    protected $model = null;

    public function initialize()
    {
        $this->wechat = Wechat::officialAccount();
        $this->model = new MenuModel;
    }
    /**
     * 菜单列表
     *
     * @return Response
     */
    public function list(): Response
    {
        $current = $this->getCurrentMenu();
        $data = $this->model->sheepFilter()->paginate(request()->param('list_rows', 10));

        return success('操作成功', ['current' => $current, 'list' => $data]);
    }

    /**
     * 菜单详情
     *
     * @param  int $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $data = $this->model->findOrFail($id);
        return success('获取成功', $data);
    }


    /**
     * 添加菜单
     *
     * @param  int $publish   发布状态:0=不发布,1=直接发布
     * @return \think\Response
     */
    public function add()
    {
        $publish = $this->request->param('publish', 0);
        $params = $this->request->only(['name', 'rules']);
        // 参数校验
        $this->svalidate($params, '.add');

        $menu = Db::transaction(function () use ($params, $publish) {
            $menu = $this->model->save($params);
            if ($publish) {
                return $this->publish($menu->id);
            }
            return $menu;
        });
        return success('保存成功', $menu);
    }

    /**
     * 编辑
     *
     * @param  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $menu = $this->model->findOrFail($id);

        $publish = $this->request->param('publish', 0);
        $params = $this->request->only(['name', 'rules']);

        // 参数校验
        $this->svalidate($params);

        $menu = Db::transaction(function () use ($params, $menu) {
            $menu->save($params);
            return $menu;
        });
        if ($publish) {
            $this->publish($menu->id);
        }

        return success('更新成功');
    }

    /**
     * 删除
     *
     * @param  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $is_real = $this->request->param('is_real', 0);
        Db::transaction(function () use ($id, $is_real) {
            $menu = $this->model->findOrFail($id);
            if ($is_real) {
                $menu->force()->delete();
            } else {
                $menu->delete();
            }
        });

        return success('删除成功');
    }

    /**
     * 发布菜单
     *
     * @param  $id
     * @return \think\Response
     */
    public function publish($id)
    {
        $menu = $this->model->findOrFail($id);

        Db::transaction(function () use ($menu) {
            $this->model->where('id', '<>', $menu->id)->update(['status' => 0]);
            if ($this->setCurrentMenu($menu->rules)) {
                $menu->save([
                    'status' => 1,
                    'publish_time' => time()
                ]);
            }
        });

        return success('发布成功');
    }

    /**
     * 复制菜单
     *
     * @return Response
     */
    public function copy($id = 0)
    {
        if ($id == 0) {
            $data = [
                'name' => '复制 当前菜单',
                'rules' => $this->getCurrentMenu(),
            ];
        } else {
            $menu = $this->model->findOrFail($id);
            $data = [
                'name' => '复制 ' . $menu->name,
                'rules' => $menu->rules
            ];
        }

        $menu = $this->model->save($data);
        return success('复制成功', $menu);
    }

    // 获取当前菜单
    private function getCurrentMenu()
    {
        $currentMenu = $this->wechat->menu->current();
        if (isset($currentMenu['selfmenu_info']['button'])) {
            $buttons = $currentMenu['selfmenu_info']['button'];
            foreach ($buttons as &$button) {
                if (isset($button['sub_button'])) {
                    $button['sub_button'] = $button['sub_button']['list'];
                }
            }
            return $buttons;
        } else {
            return [];
        }
    }

    // 设置菜单
    private function setCurrentMenu($rules)
    {
        $result = $this->wechat->menu->create($rules);

        if (isset($result['errcode']) && $result['errcode'] === 0) {
            return true;
        } else {
            throw new SheepException($result['errmsg'] ?? '发布失败');
        }
    }
}
